package one.stand.controller.home;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jmp.api.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.dto.*;
import com.jmp.feign.*;
import com.jmp.service.api.admin.BannerApi;
import com.jmp.service.api.admin.dto.BannerListDto;
import com.jmp.service.api.admin.dto.BannerListVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.*;
import one.stand.mapper.DynamicMapperExt;
import one.stand.mapper.GoodsApiCrmAppMapper;
import one.stand.model.*;
import one.stand.service.*;
import one.stand.service.user.MenuService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import one.stand.util.OneStringUtils;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author cjr
 */
@Api(description = "我的")
@RequestMapping("user")
@RestController
public class UserController {
    @Autowired
    private RecordFeign recordFeign;
    @Autowired
    private ShopCartFeign shopCartFeign;
    @Autowired
    private DynamicFeign dynamicFeign;
    @Autowired
    private OrderFeign orderFeign;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private BannerFeign bannerFeign;

    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private GoodsBaseService goodsBaseService;
    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private RecordPublicService recordPublicService;
    @Autowired
    private DynamicMapperExt dynamicMapperExt;

    @Autowired
    private GoodsApiCrmAppMapper goodsApiCrmAppMapper;

    @ApiOperation(value = "1我的")
    @PostMapping("info")
    @SecurityAuthCheck
    public ResultModel<UserInfoResponse> info() {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        UserDto user = userAdminService.get(optUser.getUserId());
        List<Menu> openMenu = menuService.getOpenMenu(optUser.getUserId(), MenuService.TYPE_CRN_APP_NEW);
        List<String> openMenuCodes = ConvertUtils.list(openMenu, Menu::getPage).stream().filter(StringUtils::isNoneBlank).collect(Collectors.toList());

        String userName = user.getName();
        if (Objects.nonNull(optUser.getCardId())) {
            BusinessCard card = businessCardBaseService.getCustomer(optUser.getCardId());
            userName = card.getName();
        }

        //我的统计 购物车、收藏、关注、评论
        ResultModel<ShopCartCountVo> resultModel = shopCartFeign.count(ShopCartCountDto.builder().userId(optUser.getUserId()).build());
        AssertUtil.isTrue(resultModel);
        Integer shopCartNum = resultModel.getData().getTotal();
        Integer followNum = getCollect(optUser.getUserId(), RecordPublicService.ITEMTYPE_COMPANY);
        Integer followUserNum = getCollect(optUser.getUserId(), RecordPublicService.ITEMTYPE_USER);
        Integer collectNum = getCollect(optUser.getUserId(), RecordPublicService.ITEMTYPE_GOODS);
        PageHelper.startPage(1, 1);
        List<CommentDto> list = recordPublicService.getCommentList(optUser.getUserId());
        Integer commentNum = Math.toIntExact(((Page) list).getTotal());

        //订单统计
        ResultModel<OrderCountVo> orderCountVoResultModel = orderFeign.count(OrderCountDto.builder().userId(optUser.getUserId()).build());
        AssertUtil.isTrue(orderCountVoResultModel);
        Integer orderPayNum = 0;
        Integer orderSendNum = 0;
        Integer orderReceiveNum = 0;
        Integer orderCompleteNum = 0;
        Integer orderRefundNum = 0;
        for (OrderCountVo.StateVo stateVo : orderCountVoResultModel.getData().getResult()) {
            if (stateVo.getOrderState() == 1) {
                orderPayNum = stateVo.getNum();
            } else if (stateVo.getOrderState() == 2) {
                orderSendNum = stateVo.getNum();
            } else if (stateVo.getOrderState() == 3) {
                orderReceiveNum = stateVo.getNum();
            } else if (stateVo.getOrderState() == 4) {
                orderCompleteNum = stateVo.getNum();
            } else if (stateVo.getOrderState() == 5) {
                orderRefundNum = stateVo.getNum();
            }
        }

        //我的banner
        BannerListDto bannerListDto = BannerListDto.builder()
                .companyId(BannerApi.COMPANY_ID_PLATFORM)
                .bannerType(BannerApi.BANNER_TYPE_USER)
                .refId(null)
                .build();
        bannerListDto.setAll();
        ResultModel<BannerListVo> bannerListVoResultModel = bannerFeign.list(bannerListDto);
        AssertUtil.isTrue(bannerListVoResultModel);
        List<UserInfoResponse.Banner> iconList = ConvertUtils.list(bannerListVoResultModel.getData().getBannerPage().getList(), companyBanner -> UserInfoResponse.Banner.builder()
                .bannerId(companyBanner.getId())
                .source(companyBanner.getSource())
                .event(companyBanner.getEvent())
                .eventId(companyBanner.getEventId())
                .memo(companyBanner.getMemo())
                .sizeRate(companyBanner.getSizeRate())
                .build());


        UserInfoResponse response = UserInfoResponse.builder()
                .userId(optUser.getUserId())
                .userName(userName)
                .name(user.getName())
                .userImg(user.getUserImg())
                .auths(openMenuCodes)
                .shopCartNum(shopCartNum)
                .followNum(followNum)
                .followUserNum(followUserNum)
                .collectNum(collectNum)
                .commentNum(commentNum)
                .orderPayNum(orderPayNum)
                .orderSendNum(orderSendNum)
                .orderReceiveNum(orderReceiveNum)
                .orderCompleteNum(orderCompleteNum)
                .orderRefundNum(orderRefundNum)
                .bannerList(iconList)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "2我的关注")
    @GetMapping("follow")
    @SecurityAuthCheck
    @Deprecated
    public ResultModel<UserFollowResponse> follow(@RequestAttribute PageRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        RecordCollectListDto collectRequest = RecordCollectListDto.builder().userId(optUser.getUserId()).type(RecordPublicService.ITEMTYPE_COMPANY).build();
        collectRequest.setPageNum(request.getPageNum());
        collectRequest.setPageSize(request.getPageSize());
        ResultModel<RecordCollectListVo> resultModel = recordFeign.collectList(collectRequest);
        AssertUtil.isTrue(resultModel);
        PageResponse2<UserFollowResponse.Company> companyPageResponse2 = ConvertUtils.page2(resultModel.getData().getPage(), collect -> {
            Company2Dto company = companyBaseService.get2(collect.getItemId());
            return UserFollowResponse.Company.builder()
                    .followId(collect.getId())
                    .companyId(collect.getItemId())
                    .companyName(company.getCompanyName())
                    .companyLogo(company.getCompanyLogo())
                    .companyLevel(company.countCompanyLevelView())
                    .zkFlag(BooleanUtils.toInteger(companyBaseService.hasZkgx(company.getCompanyId())))
                    .build();
        });

        UserFollowResponse response = UserFollowResponse.builder()
                .companyPage(companyPageResponse2)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "2我的关注(新)")
    @GetMapping("follow/user")
    @SecurityAuthCheck
    public ResultModel<UserFollowUserResponse> followUser(@RequestAttribute PageRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        RecordCollectListDto collectRequest = RecordCollectListDto.builder().userId(optUser.getUserId()).type(RecordPublicService.ITEMTYPE_USER).build();
        collectRequest.setPageNum(request.getPageNum());
        collectRequest.setPageSize(request.getPageSize());
        ResultModel<RecordCollectListVo> resultModel = recordFeign.collectList(collectRequest);
        AssertUtil.isTrue(resultModel);
        PageResponse2<UserFollowUserResponse.User> companyPageResponse2 = ConvertUtils.page2(resultModel.getData().getPage(), collect -> {
            UserDto user = userAdminService.get(collect.getItemId());
            return UserFollowUserResponse.User.builder()
                    .followId(collect.getId())
                    .userId(user.getUserId())
                    .userImg(OneStringUtils.photoResize(user.getUserImg()))
                    .userName(user.getName())
                    .build();
        });

        UserFollowUserResponse response = UserFollowUserResponse.builder()
                .companyPage(companyPageResponse2)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "3我的收藏")
    @GetMapping("collect")
    @SecurityAuthCheck
    public ResultModel<UserCollectResponse> collect(@RequestAttribute UserCollectRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        Integer typeId = Objects.nonNull(request.getTypeId()) && request.getTypeId().equals(0) ? null : request.getTypeId();
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<UserCollectResponse.Goods> goodsList = goodsApiCrmAppMapper.selectCollect(optUser.getUserId(), RecordPublicService.ITEMTYPE_GOODS, typeId);
        PageResponse2<UserCollectResponse.Goods> goodsPageResponse2 = ConvertUtils.page2(goodsList, goods -> {
            Goods goods1 = goodsBaseService.get(goods.getGoodsId());
            goods.setGoodsName(goods1.getGoodsName());
            goods.setPhoto(OneStringUtils.photoResize(goodsPhotoService.getPath(goods.getGoodsId())));
            goods.setPrice(goods1.getPrice());
            return goods;
        });

        List<UserCollectResponse.Type> goodsTypeList = null;
        if (request.getPageNum() == 1) {
            List<GoodsType> goodsTypes = goodsTypeService.getParent(GoodsTypeService.PLATFORM_COMPANY_ID);
            goodsTypeList = ConvertUtils.list(goodsTypes, goodsType -> {
                return UserCollectResponse.Type.builder()
                        .typeId(goodsType.getGoodstypeId())
                        .typeName(goodsType.getName())
                        .build();
            });
        }

        UserCollectResponse response = UserCollectResponse.builder()
                .goodsPage(goodsPageResponse2)
                .typeList(goodsTypeList)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "3批量取消收藏")
    @PostMapping("collect/remove")
    @SecurityAuthCheck
    public ResultModel collectRemove(@RequestAttribute UserCollectRemoveRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        for (Integer goodsId : request.getGoodsIds()) {
            ResultModel<RecordCollectionVo> resultModel = recordFeign.collection(RecordCollectionDto.builder()
                    .userId(optUser.getUserId())
                    .itemType(RecordPublicService.ITEMTYPE_GOODS)
                    .itemId(goodsId)
                    .build());
            AssertUtil.isTrue(resultModel);
        }

        return ResultModel.success();
    }

    @ApiOperation(value = "4编辑信息：保存")
    @PostMapping("save")
    @SecurityAuthCheck
    public ResultModel save(@RequestAttribute UserSaveRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        ResultModel resultModel = userFeign.save(UserSaveDto.builder()
                .id(optUser.getUserId())
                .nickeName(request.getUserName())
                .avatarUrl(request.getUserImg())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation(value = "5我的评论", notes = "管理是长按该评论")
    @GetMapping("comment")
    @SecurityAuthCheck
    public ResultModel<UserCommentResponse> comment(@RequestAttribute PageRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        UserDto user = userAdminService.get(optUser.getUserId());

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CommentDto> list = recordPublicService.getCommentList(optUser.getUserId());
        PageResponse2<UserCommentResponse.Comment> page = ConvertUtils.page2(list, commentDto -> {
            Dynamic dynamic = dynamicMapperExt.selectByPrimaryKey(commentDto.getDynamicId());
            List<String> photos = StrUtil.split(dynamic.getPhotos(), CharUtil.COMMA);
            return UserCommentResponse.Comment.builder()
                    .commentId(commentDto.getCommentId())
                    .content(commentDto.getText())
                    .time(commentDto.getCreateTime().getTime())
                    .dynamicId(dynamic.getDynamicId())
                    .type(dynamic.getType())
                    .dynamicPhoto(CollUtil.isNotEmpty(photos) ? photos.get(0) : null)
                    .userImg(user.getUserImg())
                    .userId(user.getUserId())
                    .build();
        });

        UserCommentResponse response = UserCommentResponse.builder()
                .commentPage(page)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "5我的评论: 批量删除")
    @PostMapping("/comment/remove")
    @SecurityAuthCheck
    public ResultModel commentRemove(@RequestAttribute UserCommentRemoveRequest request) {
        AssertUtil.nonNull(request.getCommentIds(), ResultEnum.PARAM_CHECK, "评论ID不能为空");

        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        ResultModel resultModel = dynamicFeign.commentRemove(DynamicCommentRemoveDto.builder()
                .commentIds(request.getCommentIds())
                .userId(optUser.getUserId())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    private Integer getCollect(Integer userId, Integer type) {
        RecordCollectListDto collectRequest = RecordCollectListDto.builder().userId(userId).type(type).build();
        collectRequest.setPageNum(1);
        collectRequest.setPageSize(1);
        ResultModel<RecordCollectListVo> resultModel = recordFeign.collectList(collectRequest);
        AssertUtil.isTrue(resultModel);
        return resultModel.getData().getPage().getTotal().intValue();
    }
}
